package org.dromara.mqtt.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.dromara.mqtt.service.MqttMessageHandler;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CustomMqttMessageHandler implements MqttMessageHandler {

    @Override
    public void handleMessage(String topic, String message) {
        // 自定义消息处理逻辑
        log.info("Custom Handler - Topic: {}, Message: {}", topic, message);

        // 根据主题进行不同的处理
        if (topic.endsWith("/temperature")) {
            handleTemperatureData(message);
        } else if (topic.endsWith("/humidity")) {
            handleHumidityData(message);
        } else {
            handleGenericMessage(topic, message);
        }
    }

    private void handleTemperatureData(String message) {
        try {
            double temperature = Double.parseDouble(message);
            log.info("处理温度数据: {}°C", temperature);
            // 可以在这里添加温度数据的处理逻辑，如存储到数据库等
        } catch (NumberFormatException e) {
            System.err.println("无效的温度数据格式: " + message);
        }
    }

    private void handleHumidityData(String message) {
        try {
            double humidity = Double.parseDouble(message);
            log.info("处理湿度数据: {}%", humidity);
            // 可以在这里添加湿度数据的处理逻辑
        } catch (NumberFormatException e) {
            System.err.println("无效的湿度数据格式: " + message);
        }
    }

    private void handleGenericMessage(String topic, String message) {
        log.info("处理通用消息 - Topic: {}, Message: {}", topic, message);
        // 通用消息处理逻辑
    }
}
